package com.haredot.config;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haredot.constraint.RabbitConst;
import com.haredot.entity.Order;
import com.haredot.entity.enums.OrderStatus;
import com.haredot.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Configuration
@Slf4j
public class OrderConfig {

    @Resource
    private OrderMapper orderMapper ;

    @Bean("orderQueue")
    public Queue orderQueue() {
        return QueueBuilder
                .durable(RabbitConst.ORDER_QUEUE)
                .deadLetterExchange(RabbitConst.DEAD_LETTER_ORDER_EXCHANGE)
                .deadLetterRoutingKey(RabbitConst.DEAD_LETTER_ORDER_ROUTING_KEY)
                .ttl(30 * 60 * 1000)
                .build();
    }

    @Bean("orderExchange")
    public DirectExchange orderExchange() {
        return new DirectExchange(RabbitConst.ORDER_EXCHANGE, true, false);
    }

    @Bean
    public Binding bindingOrderQueueAndExchange(@Qualifier("orderQueue") Queue orderQueue,
                                                @Qualifier("orderExchange") DirectExchange orderExchange) {

        return BindingBuilder.bind(orderQueue).to(orderExchange).with(RabbitConst.ORDER_ROUTING_KEY);
    }



    @Bean("orderDeadLetterQueue")
    public Queue orderDeadLetterQueue() {
        return QueueBuilder
                .durable(RabbitConst.DEAD_LETTER_ORDER_QUEUE)
                .build();
    }

    @Bean("orderDeadLetterExchange")
    public DirectExchange orderDeadLetterExchange() {
        return new DirectExchange(RabbitConst.DEAD_LETTER_ORDER_EXCHANGE, true, false);
    }

    @Bean
    public Binding bindingDeadLetterOrderQueueAndExchange(@Qualifier("orderDeadLetterQueue") Queue orderQueue,
                                                @Qualifier("orderDeadLetterExchange") DirectExchange orderExchange) {

        return BindingBuilder.bind(orderQueue).to(orderExchange).with(RabbitConst.DEAD_LETTER_ORDER_ROUTING_KEY);
    }

    @DS("rss")
    @RabbitListener(queues = RabbitConst.DEAD_LETTER_ORDER_QUEUE)
    public void cancelOrder(Channel channel , Message message) throws Exception {
        // 获取消息内容 （订单编号）
        String orderNum = new String(message.getBody(), StandardCharsets.UTF_8);
        // 调用 查询 订单的 接口
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_num", orderNum));

        if (order == null) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return ;
        }
        // 如果订单编号存在， 则 检查 该笔的状态
        if ( order.getState() != OrderStatus.WAIT_BUYER_PAY) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return ;
        }
        // 如果 该笔订单是 待付款，则 取消订单
        order.setState(OrderStatus.TRADE_CLOSED);
        orderMapper.updateById(order);

        log.info("订单编号为 {} 被自动取消", orderNum);
        // 进行 正面确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
